package com.huihui.activity;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.huihui.R;
import com.huihui.adapter.ChildCommentAdapter;
import com.huihui.base.BaseActivity;
import com.huihui.bean.Comment;
import com.huihui.datamanager.AppManager;
import com.huihui.network.HttpContants;
import com.huihui.network.OkHttpRequest;
import com.huihui.network.base.CallBackUtil;
import com.huihui.utils.IntentUtils;
import com.huihui.utils.LoadImageUtil;
import com.huihui.widget.SwipeRecyclerView;
import com.huihui.widget.dialog.ReplyOrCopyDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;

public class CommentListActivity extends BaseActivity implements View.OnClickListener {

    private Comment mComment;
    private List<Comment> childCommentList;
    private Comment childComment;
    private LinearLayout inputLayout;
    private EditText inputText;
    private int class_id;
    private long relation_id;
    private ChildCommentAdapter childCommentAdapter;
    private long parent_id;
    private SwipeRecyclerView recyclerView;
    private int pageIndex = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comment_list);
        initIntentData();
        initView();
        initCommentList();
        initListener();
    }

    private void initListener() {
        recyclerView.setOnLoadListener(new SwipeRecyclerView.OnLoadListener() {
            @Override
            public void onRefresh() {
                pageIndex = 1;
                initCommentList();
            }

            @Override
            public void onLoadMore() {
                pageIndex++;
                initCommentList();
            }
        });
    }

    private void initView() {
        inputLayout = findViewById(R.id.inuput_layout);
        inputText = findViewById(R.id.input_text);
        CircleImageView headView = findViewById(R.id.head_view);
        TextView userName = findViewById(R.id.user_name);
        TextView user_time = findViewById(R.id.user_time);
        ImageView zanIcon = findViewById(R.id.detail_zan_icon);
        TextView zanCount = findViewById(R.id.zanCount);
        TextView comment_content = findViewById(R.id.comment_content);

        LoadImageUtil.displayImage(this, mComment.getUser_head_photo(), headView);
        userName.setText(mComment.getUser_nick_name());
        user_time.setText(mComment.getCom_time());
        int is_Like = mComment.getIs_like();
        if (is_Like == 1) {
            zanIcon.setImageResource(R.mipmap.zan_press);
        } else {
            zanIcon.setImageResource(R.mipmap.zan);
        }
        zanCount.setText(String.valueOf(mComment.getCollection_num()));
        comment_content.setText(mComment.getCom_content());
        recyclerView = findViewById(R.id.child_comment_list);
//        childCommentList = mComment.getSub_comm();
        childCommentList =new ArrayList<>();
//        childCommentAdapter = new ChildCommentAdapter(this, R.layout.chile_comment_item2, childCommentList);
//        listView.setAdapter(childCommentAdapter);
        recyclerView.getSwipeRefreshLayout()
                .setColorSchemeColors(getResources().getColor(R.color.colorPrimary));
        setRecycleView(recyclerView);
        recyclerView.setRefreshing(true);

        childCommentAdapter = new ChildCommentAdapter(this, childCommentList);
        recyclerView.setAdapter(childCommentAdapter);
        initEvent(childCommentAdapter);
    }

    private void initEvent(ChildCommentAdapter childCommentAdapter) {
        childCommentAdapter.setOnChildCommentListener(new ChildCommentAdapter.OnChildCommentListener() {
            @Override
            public void onClick(int position) {
                childComment = childCommentList.get(position);
                showReplyOrCopyDialog(position);

            }
        });

        inputText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                String content = v.getText().toString();
                if (TextUtils.isEmpty(content)) {
                    return false;
                }
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    if (childComment == null) {

                        replyComment(content, mComment.getCom_id());
                    } else {
                        replyComment(content, childComment.getCom_id());
                    }
                    hideInputKeyboard();
                }

                return false;
            }
        });
    }

    private void showInputKeyboard() {
        inputText.setHint("回复 " + childComment.getUser_nick_name());
        showInput2(CommentListActivity.this, inputText);

    }

    private void hideInputKeyboard() {
        inputText.setHint("写评论");
        inputText.getText().delete(0, inputText.getText().toString().length());
        hideInput(CommentListActivity.this);
    }

    private void initIntentData() {
        Intent intent = getIntent();
        mComment = (Comment) intent.getSerializableExtra("Comment");
        class_id = intent.getIntExtra("class_id", 0);
        relation_id = intent.getLongExtra("relation_id", 0);
        parent_id = mComment.getCom_id();
//        getSupportActionBar().setTitle(mComment.getSub_comm().size() + "条回复");
        titleView.setText(mComment.getSub_comm().size() + "条回复");
    }

//
//    private class ChildCommentAdapter extends CommonAdapter<Comment> {
//        private Context context;
//
//        public ChildCommentAdapter(Context context, int layoutId, List<Comment> datas) {
//            super(context, layoutId, datas);
//            this.context = context;
//        }
//
//        @Override
//        protected void convert(ViewHolder viewHolder, Comment item, int position) {
//            CircleImageView headView = viewHolder.getView(R.id.head_view);
//            TextView user_name = viewHolder.getView(R.id.user_name);
//            TextView user_time = viewHolder.getView(R.id.user_time);
//            ImageView zanIcon = viewHolder.getView(R.id.zanIcon);
//            TextView zanCount = viewHolder.getView(R.id.zanCount);
//            PartColorTextView comment_content = viewHolder.getView(R.id.comment_content);
//
//            LoadImageUtil.displayImage(context, item.getUser_head_photo(), headView);
//            user_name.setText(item.getUser_nick_name());
//            user_time.setText(item.getCom_time());
//            int is_Like = item.getIs_like();
//            if (is_Like == 1) {
//                zanIcon.setImageResource(R.mipmap.zan_press);
//            } else {
//                zanIcon.setImageResource(R.mipmap.zan);
//            }
//            zanCount.setText(String.valueOf(item.getCollection_num()));
//            comment_content.setText(item.getCom_content());
//            LinearLayout item2_layout = viewHolder.getView(R.id.item2_layout);
//            if (listener != null) {
//                item2_layout.setTag(position);
//                item2_layout.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        int p = (int) v.getTag();
//                        listener.onClick(p);
//                    }
//                });
//            }
//        }
//
//        private OnChildCommentListener listener;
//
//        private void setOnChildCommentListener(OnChildCommentListener listener) {
//            this.listener = listener;
//        }
//
//    }
//
//    public interface OnChildCommentListener {
//        void onClick(int position);
//    }

    /**
     * 回复评论
     * 二级评论
     *
     * @param com_id 被回复的评论id
     */
    private void replyComment(String content, int com_id) {
        if (class_id == 0) {
            addProductComment(content, com_id);
        } else if (class_id == 1) {

        } else if (class_id == 2) {
            addAriticleComment(content, com_id);
        }
    }

    private void addAriticleComment(String content, final int parentCommentId) {
        OkHttpRequest.getInstance().addArticleComment(HttpContants.article_addComment, AppManager.getUserInfo().getUser_id(), relation_id,
                parentCommentId, content, new CallBackUtil.CallBackString() {
                    @Override
                    public void onFailure(Call call, Exception e) {

                    }

                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject articleObject = new JSONObject(response);
                            if (articleObject != null && articleObject.has(HttpContants.STATE) && articleObject.getInt(HttpContants.STATE) == 10000) {

                                initCommentList();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    /**
     * 添加评论
     *
     * @param content         评论内容
     * @param parentCommentId 父评论id （0 没有，其他 有）
     */
    private void addProductComment(String content, final int parentCommentId) {
        OkHttpRequest.getInstance().addProductComment(HttpContants.product_addComment, AppManager.getUserInfo().getUser_id(), relation_id,
                parentCommentId, content, new CallBackUtil.CallBackString() {
                    @Override
                    public void onFailure(Call call, Exception e) {

                    }

                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject productObject = new JSONObject(response);
                            if (productObject != null && productObject.has(HttpContants.STATE) && productObject.getInt(HttpContants.STATE) == 10000) {
                                initCommentList();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });

    }

    private void initCommentList() {
        OkHttpRequest.getInstance().getChildComment(HttpContants.get_childCommentList, relation_id, class_id, parent_id,10,pageIndex, new CallBackUtil.CallBackString() {
            @Override
            public void onFailure(Call call, Exception e) {
                recyclerView.setRefreshing(false);
            }

            @Override
            public void onResponse(String response) {
                recyclerView.setRefreshing(false);
                try {
                    JSONObject productObject = new JSONObject(response);
                    if (productObject != null && productObject.has(HttpContants.DATA)) {
                        List<Comment> list = AppManager.getGson().fromJson(productObject.getString(HttpContants.DATA), new TypeToken<List<Comment>>() {
                        }.getType());
                        if (list != null) {
                            if (pageIndex == 1) {
                                childCommentList.clear();
                                childCommentList.addAll(list);
                                childCommentAdapter.notifyDataSetChanged();
                            } else {
                                childCommentList.addAll(list);
                                childCommentAdapter.notifyDataSetChanged();
                            }
                            if (list.size() < 10){
                                recyclerView.setLoadMoreEnable(false);
                            }else{
                                recyclerView.setLoadMoreEnable(true);
                            }
                        }else{
                            recyclerView.setLoadMoreEnable(false);
                        }
                    }else{
                        recyclerView.setLoadMoreEnable(false);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        //文章

    }

    private ReplyOrCopyDialog recplyAndCopyDialog;

    /**
     * 显示 回复，复制diloag
     *
     * @param position 评论 position
     */
    private void showReplyOrCopyDialog(int position) {
        childComment = childCommentList.get(position);
        if (recplyAndCopyDialog == null) {
            recplyAndCopyDialog = new ReplyOrCopyDialog(this);
            recplyAndCopyDialog.addClickListener(this);
        }
        recplyAndCopyDialog.show();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.reply_id:
                if (recplyAndCopyDialog.isShowing()) {
                    recplyAndCopyDialog.dismiss();
                }
                showInputKeyboard();

                break;
            case R.id.copy_id:
                if (recplyAndCopyDialog.isShowing()) {
                    recplyAndCopyDialog.dismiss();
                }
                String commentCopy = childComment.getCom_content();
                copyContent(commentCopy);
                break;
            case R.id.comment_id:
                if (recplyAndCopyDialog.isShowing()) {
                    recplyAndCopyDialog.dismiss();
                }
                int id = 0;
                if(class_id == 0){
                    id = 1;
                }else if(class_id == 2){
                    id = 4;
                }
                if(childComment !=null) {
                    IntentUtils.gotoReportAnswerActivity(this, childComment.getUser_nick_name(),childComment.getUser_id(),childComment.getCom_id(),id,childComment.getCom_content());
                }
                break;
            default:
                break;
        }
    }

    /**
     * 复制文本
     *
     * @param content 需要复制的内容
     */
    private void copyContent(String content) {
        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        cm.setPrimaryClip(ClipData.newPlainText(null, content));
        Toast.makeText(this, "复制成功", Toast.LENGTH_LONG).show();
    }
}
